package com.smart.tool.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @Author xiaoqiang
 * @Version JsonTool.java, v 0.1 2025年05月18日 20:54 xiaoqiang
 * @Description: Jackson工具类
 */
public class JacksonTool {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Logger logger = LoggerFactory.getLogger(JacksonTool.class);

    static {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    }

    /**
     * Convert an object to a JSON string
     *
     * @param object the object to convert
     * @return the JSON string
     * @throws JsonProcessingException if an error occurs during JSON processing
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("toJson exception",e);
        }
    }

    /**
     * Parse a JSON string as the specified type
     *
     * @param json      the JSON string to parse
     * @param valueType the class of the value type
     * @param <T>       the value type
     * @return the parsed value
     */
    public static <T> T fromJson(String json, Class<T> valueType) {
        try {
            return objectMapper.readValue(json, valueType);
        } catch (Exception e) {
            throw new RuntimeException("fromJson exception",e);
        }

    }

    /**
     * Parse a JSON string using the specified TypeReference
     *
     * @param json          the JSON string to parse
     * @param typeReference the TypeReference for the value type
     * @param <T>           the value type
     * @return the parsed value
     * @throws IOException if an error occurs during JSON processing
     */
    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            throw new RuntimeException("fromJson exception",e);
        }

    }

    /**
     * Parse a JSON string using the specified JavaType
     *
     * @param json     the JSON string to parse
     * @param javaType the JavaType for the value type
     * @param <T>      the value type
     * @return the parsed value
     * @throws IOException if an error occurs during JSON processing
     */
    public static <T> T fromJson(String json, JavaType javaType) {
        try {
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            throw new RuntimeException("fromJson exception",e);
        }
    }
}
